<template>
  <el-dialog
    ref="refDlg"
    :title="(flag === 'detail' ? '详情' : (queryObj.id ? '编辑' : '新增'))"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="800px"
    @close="closeDialog"
  >
    <div>
      <div>
        <div class="qup-title-box"><span class="border" /><span>考核类别信息</span></div>
        <el-form ref="refForm" class="my-form" size="mini" :rules="formRules" :model="queryObj" label-width="90px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="评估性质:" prop="scoreNature">
                <span v-if="flag === 'detail'">{{ formaterData(scoreMatureList, queryObj.scoreNature) }}</span>
                <el-select v-else v-model="queryObj.scoreNature" size="mini" placeholder="请选择评估性质" style="width:100%">
                  <el-option v-for="item in scoreMatureList" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="考核类别:" prop="scoreType">
                <span v-if="flag === 'detail'">{{ queryObj.scoreType }}</span>
                <el-input v-else v-model="queryObj.scoreType" placeholder="请输入考核类别" size="mini" maxlength="128" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总分值:" prop="totalScore">
                <span v-if="flag === 'detail'">{{ queryObj.totalScore }}</span>
                <el-input v-else v-model.number="queryObj.totalScore" min="1" max="100" placeholder="请输入总分值" size="mini" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="考核说明:" prop="scoreDesc">
                <span v-if="flag === 'detail'">{{ queryObj.scoreDesc }}</span>
                <el-input v-else v-model="queryObj.scoreDesc" placeholder="请输入考核说明" size="mini" maxlength="128" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="qup-title-box"><span class="border" /><span>考核明细信息</span></div>
      <div v-if="flag !== 'detail'" class="btn-group">
        <el-button type="primary" size="mini" @click="handleAdd">新增</el-button>
        <el-button type="primary" size="mini" @click="handleDel">删除</el-button>
      </div>
      <el-table
        v-loading="tableLoading"
        element-loading-text="加载中"
        :data="tableData"
        :default-sort="{prop: 'date', order: 'descending'}"
        :header-cell-style="{background:'#f2f2f2',border:'1px solid #EBEEF5'}"
        border
        highlight-current-row
        @selection-change="selectionChangeHandle"
      >
        <el-table-column v-if="flag !== 'detail'" type="selection" width="55" />
        <el-table-column prop="detailItem" label="明细项目" sortable min-width="200">
          <template slot="header">
            <span style="color: red">*</span>明细项目
          </template>
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ scope.row.detailItem }}</span>
            <el-input v-else ref="materialInput" v-model.trim="scope.row.detailItem" size="mini" placeholder="请输入明细项目" maxlength="128" @blur="checkDetailItem(scope.row)" />
          </template>
        </el-table-column>

        <el-table-column prop="grading" label="评分标准" sortable min-width="150">
          <template slot="header">
            <span style="color: red">*</span>评分标准
          </template>
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ scope.row.grading }}</span>
            <el-input v-else v-model="scope.row.grading" placeholder="请输入评分标准" maxlength="128" size="mini" />
          </template>
        </el-table-column>

        <el-table-column prop="calculation" label="计算方式" sortable min-width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.id">{{ scope.row.calculation }}</span>
            <el-input v-else v-model="scope.row.calculation" placeholder="请输入原计算方式" maxlength="128" size="mini" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getDictByPatchType } from '@/api/dataDict'
import { saveScoreCriteria, queryScoreCriteria } from '@/api/constructionUnitMng'
export default {
  name: 'AddScoringCriteria',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    const validateScore = (rule, value, callback) => {
      if (!value || value.length === 0) {
        return callback(new Error('请输入总分值'))
      } else {
        if (isNaN(Number(value)) || Number(value) <= 0 || Number(value) > 100) {
          return callback(new Error('请输入1~100的整数'))
        }
      }
      callback()
    }
    return {
      scoreMatureList: [],
      queryObj: {
        id: ''
      },
      flag: '',
      tableData: [],
      selectedRows: [],
      formRules: {
        scoreNature: [{ required: true, message: '请选择评估性质' }],
        scoreType: [{ required: true, message: '请输入考核类别' }],
        totalScore: [{ required: true, message: '请输入总分值' },
          // { type: 'number', message: '请输入正整数' },
          { validator: validateScore, message: '请输入1~100的整数' }]
      }
    }
  },

  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
    // 选中行id
    // selectedIds() {
    //   return this.selectedRows.map(row => {
    //     return row.id
    //   })
    // }
  },
  created() {
    const data = this.detailData.data
    if (data && data.id) {
      queryScoreCriteria(data.id).then(res => {
        this.queryObj = res.data
        this.tableData = this.queryObj.configScoreDetailDTOS
      })
      // this.queryObj = JSON.parse(JSON.stringify(data))
      // this.tableData = this.queryObj.configScoreDetailDTOS
      this.flag = this.detailData.flag
      if (this.flag !== 'detail') {
        const validateScore = (rule, value, callback) => {
          if (!value || value.length === 0) {
            return callback(new Error('请输入总分值'))
          } else {
            if (isNaN(Number(value)) || Number(value) <= 0 || Number(value) > 100) {
              return callback(new Error('请输入1~100的整数'))
            }
          }
          callback()
        }
        this.formRules = {
          scoreNature: [{ required: true, message: '请选择评估性质' }],
          scoreType: [{ required: true, message: '请输入考核类别' }],
          totalScore: [{ required: true, message: '请输入总分值' },
            { validator: validateScore, message: '请输入1~100的整数' }]
        }
      } else {
        this.formRules = {}
      }
    }
    this.getDictByPatchTypeAll(['SCORE_NATURE']).then(res => {
      this.scoreMatureList = res.SCORE_NATURE
    })
  },

  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    checkDetailItem(row) {
      const value = row.detailItem
      const flag = this.tableData.filter(item => (item.detailItem.length && item.detailItem === value))
      if (flag.length > 1) {
        this.$message.warning('明细项目已存在，请重新输入')
        row.detailItem = ''
      }
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.selectedRows = rows
    },
    // 删除
    handleDel() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择【删除】项')
        return
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.tableData.length === this.selectedRows.length) {
          this.tableData = []
          return
        }
        const tmpData = this.tableData.filter(row => {
          const index = this.selectedRows.findIndex(v => v.detailItem === row.detailItem)
          return index === -1
        })
        this.tableData = tmpData
        this.selectedRows = []
        this.$refs.refTable.clearSelection()
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },
    // 关闭弹窗前的回调
    clearForm(done) {
      this.queryObj = {
        id: null
      }
      this.tableData = []
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 提交表单处理
    submitForm() {
      if (this.submiting) return
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          if (!this.tableData.length) {
            this.$message.warning('请增加考核明细')
            return
          }
          const flag = this.tableData.some(item => (!item.detailItem.length || !item.grading.length))
          if (flag) {
            this.$message.warning('请完善表格数据')
            return
          }
          this.queryObj.configScoreDetailDTOS = this.tableData
          this.submiting = true
          saveScoreCriteria(this.queryObj).then(res => {
            this.submiting = false
            if (res.success === 1) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.closeDialog()
              const isNew = !this.queryObj.id // 是否新增数据 true (新增则刷新列表到第一页)/ false (非新增则刷新当前页)
              this.$emit('success', isNew)
            }
          }).catch(() => {
            this.submiting = false
          })
        }
      })
    },
    // // 新增表格数据
    // handleAdd() {
    //   const tableArr = this.tableData.filter(row => row.enableAddEdit === true)
    //   if (tableArr.length === 0) {
    //     this.addEmptyRow()
    //   }
    // },
    // 新增一行空白
    handleAdd() {
      // if (this.queryObj.productCode) {
      this.tableData.unshift({
        id: '',
        detailItem: '',
        grading: '',
        calculation: ''
      })
      // } else {
      //   this.$message.warning('请选择产品')
      // }
    }
  }
}
</script>
<style lang='scss' scoped>
.img-upload-container {
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: center;
  .icon-msg{
    margin-left: 10px;
    color: #999;
  }
}
</style>
